package stats.security.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import stats.security.dao.SecurityDao;
import stats.security.dto.User;

public class SecurityDaoImpl extends HibernateDaoSupport implements SecurityDao {

    private static final String ENTITY_USER = "User";

    @SuppressWarnings("unchecked")
    @Override
    public User loadUserByEmail(String email) {
        DetachedCriteria cr = DetachedCriteria.forEntityName(ENTITY_USER);
        cr.add(Restrictions.eq("email", email));
        List<User> res = (List<User>) getHibernateTemplate().findByCriteria(cr);
        if (res.size() == 1) {
            return res.get(0);
        }
        return null;
    }

    @Override
    public User loadUserByName(String name) {
        DetachedCriteria cr = DetachedCriteria.forEntityName(ENTITY_USER);
        cr.add(Restrictions.eq("name", name));
        List<User> res = (List<User>) getHibernateTemplate().findByCriteria(cr);
        if (res.size() == 1) {
            return res.get(0);
        }
        return null;
    }

    @Override
    @Transactional(readOnly = false)
   
    
    public void saveUser(User user) {
       
    	
    getHibernateTemplate().saveOrUpdate(ENTITY_USER, user);        
        

    }

}
